<template>
  <div>
    <form-create
      v-model="footform"
      v-model:api="fApi"
      :rule="createFormRule"
      :option="createFormOptions"
    ></form-create>
    <div class="text-center">
      <el-button v-if="showSubmitBtn" type="primary" @click="onSubmit"
        >提交</el-button
      >
      <el-button v-if="showSubmitBtn" type="default" @click="onReset"
        >重置</el-button
      >
      <el-button v-if="showSubmitBtn" type="primary" @click="handleClose"
        >取消</el-button
      >
    </div>
  </div>
</template>
<script setup>
import { reactive, ref, toRefs } from "vue";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import {
  getCustomFormByKey,
  createCustomFormData,
} from "@/api/footform/custom-form";
import { onMounted } from "vue";

let route = useRoute();
let router = useRouter();
const props = defineProps({
  showSubmitBtn: {
    type: Boolean,
    default: true,
  },
});
//表单实例对象
const footform = reactive({});
const fApi = ref({});
const { showSubmitBtn } = toRefs(props);
function handleClose() {
  router.back();
}

onMounted(() => {
  getDetail();
});

const createFormRule = ref([]);
async function getDetail() {
  const res = await getCustomFormByKey(route.params.key);
  createFormRule.value = JSON.parse(res.data.structure);
}

const createFormOptions = {
  submitBtn: false,
  resetBtn: false,
  global: {
    upload: {
      props: {
        // 上传成功回调
        onSuccess: (response, file) => {
          //返回上传链接（通用，这样设置插插件才能获取到上传回调文件地址）
          file.url = response.message;
        },
        onError: function () {
          ElMessage({
            message: "上传失败！",
            type: "error",
          });
        },
      },
    },
  },
};

//提交表单数据
function onSubmit() {
  fApi.value.submit((formData) => {
    const data = reactive({
      formKey: route.params.key,
      originalData: JSON.stringify(formData),
    });
    createCustomFormData(data);
    router.back();
    ElMessage({
      message: "上传成功！",
      type: "success",
    });
  });
}

function onReset() {
  fApi.value.resetFields();
}
</script>
